package fun.diaoer.common;

import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * HttpClient  工具类
 * @author xiaodiannao
 *
 */
@Slf4j
@Component
public class HttpClientUtil {
	
	@Autowired
	private CloseableHttpClient httpClient;
	@Autowired
    private RequestConfig config;
	
	public static String getHostName() {
		String hostName=null;
		try {
			InetAddress addr = InetAddress.getLocalHost();
			hostName=addr.getHostName();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return hostName;
	}
	
	public static boolean isJobLeader() {
		try {
			InetAddress addr = InetAddress.getLocalHost();
			String hostName=addr.getHostName();
			if("GUOGUO".equals(hostName)) {
				return true;
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
			log.info("判断是否是job主机ip出错:{}",e.getMessage());
		}
		return false;
	}
	
	/**
	 * get
	 * @param httpGet
	 */
	public void setGetHeader(HttpGet httpGet){
		int uaIndex=(int)(Math.random()*Contants.userAgents.length);
		httpGet.setHeader("User-Agent",Contants.userAgents[uaIndex]);
	}
	
	/**
	 * post
	 * @param httpGet
	 */
	public void setPostHeader(HttpPost httpPost){
		int uaIndex=(int)(Math.random()*Contants.userAgents.length);
		httpPost.setHeader("User-Agent",Contants.userAgents[uaIndex]);
	}
	
	/**
	 * 不带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
	 * 
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public String doGet(String url,String encodeing) throws Exception {
		// 声明 http get 请求
		HttpGet httpGet = new HttpGet(url);
		setGetHeader(httpGet);
		// 装载配置信息
		httpGet.setConfig(config);
		String encode=StringUtils.isBlank(encodeing)?"UTF-8":"gb2312";
		// 发起请求
		HttpResponse response =HttpConnectionManager.getHttpClient().execute(httpGet); // this.httpClient.execute(httpGet);
		// 判断状态码是否为200
		if (response.getStatusLine().getStatusCode() == 200) {
			// 返回响应体的内容
			return EntityUtils.toString(response.getEntity(),encode);
		}
		return null;
	}

	/**
	 * 带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
	 * 
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public String doGet(String url, Map<String, Object> map,String encodeing) throws Exception {
		URIBuilder uriBuilder = new URIBuilder(url);
		if (map != null) {
			// 遍历map,拼接请求参数
			for (Map.Entry<String, Object> entry : map.entrySet()) {
				uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
			}
		}
		String encode=StringUtils.isBlank(encodeing)?"UTF-8":"gb2312";
		// 调用不带参数的get请求
		return this.doGet(URLDecoder.decode(uriBuilder.build().toString(), "UTF-8"),encode);
	}

	/**
	 * 带参数的post请求
	 * @param url
	 * @param map
	 * @return
	 * @throws Exception
	 */
	public String doPost(String url, Map<String, Object> map) throws Exception {
		// 声明httpPost请求
		HttpPost httpPost = new HttpPost(url);
		setPostHeader(httpPost);
		// 加入配置信息
		httpPost.setConfig(config);
		// 判断map是否为空，不为空则进行遍历，封装from表单对象
		if (map != null) {
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			for (Map.Entry<String, Object> entry : map.entrySet()) {
				list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
			}
			// 构造from表单对象
			UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");

			// 把表单放到post里
			httpPost.setEntity(urlEncodedFormEntity);
		}
		// 发起请求
		HttpResponse response = HttpConnectionManager.getHttpClient().execute(httpPost); //this.httpClient.execute(httpPost);
		if (response.getStatusLine().getStatusCode() == 200) {
			return EntityUtils.toString(response.getEntity(), "UTF-8");
		}
		return null;
	}
	

}
